package com.ltmall.api.controller;

import com.ltmall.api.bean.*;
import com.ltmall.api.constant.FrontConstants;
import com.ltmall.api.entity.JsonGroupDetail;
import com.ltmall.api.enums.DirectSupplyAreaTypeEnum;
import com.ltmall.api.manager.DirectSupplyGoodsManager;
import com.ltmall.api.manager.DirectSupplyManager;
import com.ltmall.api.util.LocationUtils;
import com.ltmall.api.util.RemoteUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 小区直供控制器
 *
 * @author dou.guo
 * @Title DirectSupplyController.java
 * @Description 类DirectSupplyController.java的实现描述：类实现描述
 * @date 2017年10月10日 上午11:06:16
 * @package com.ltmall.api.controller
 */
@Controller
public class DirectSupplyController {

    private static Logger logger = LogManager.getLogger(DirectSupplyController.class);

    private DirectSupplyManager directSupplyManager;

    private DirectSupplyGoodsManager directSupplyGoodsManager;

    /**
     * 获取当前区域下开通直供的子级区域
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    public void getDirectSupplyArea(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {

        String curAreaName = request.getParameter("curAreaName");
        //curAreaName = new String(curAreaName.getBytes("ISO-8859-1"), "utf-8");
        String areaTypeStr = request.getParameter("areaType");

        DirectSupplyAreaTypeEnum areaType = DirectSupplyAreaTypeEnum.getEnumByCode(areaTypeStr);
        //错误的枚举
        if (areaType == null) {
            logger.info("获取当前区域下开通直供的子级区域时发生异常，异常信息：错误的区域枚举类型");
            RemoteUtil.response(response, null, -2, "请稍后重试");
        }

        List<ThDirectSupply> areas = directSupplyManager.getOpenedArea(curAreaName, areaType);

        RemoteUtil.response(response, areas, 1, "返回成功");
    }

    /**
     * 获取所有开通的小区列表
     *
     * @param request
     * @param response
     */
    public void getDirectSupplyList(HttpServletRequest request, HttpServletResponse response) {

        List<ThDirectSupply> areas = directSupplyManager.getDirectSupplyList();

        RemoteUtil.response(response, areas, 1, "返回成功");
    }

    /**
     * 开通小区直供
     *
     * @param request
     * @param response
     */
    public void openDirectSupply(HttpServletRequest request, HttpServletResponse response) {

        try {
            ThDirectSupply order = (ThDirectSupply) RemoteUtil.request(request,
                    new ThDirectSupply());

            boolean flag = directSupplyManager.openDirectSupply(order);

            logger.info("开通小区直供，返回结果为：" + flag);

            if (!flag) {
                RemoteUtil.response(response, null, -2, "操作失败");
            } else {
                RemoteUtil.response(response, null, 1, "返回成功");
            }

        } catch (Exception e) {
            logger.error("");
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    /**
     * 通过id查询开通小区详情信息
     *
     * @param request
     * @param response
     */
    public void getDirectSupplyById(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id");
            if (StringUtils.isEmpty(id)) {
                RemoteUtil.response(response, null, -2, "操作失败");
                return;
            }

            ThDirectSupply data = directSupplyManager.getDirectSupplyById(id);

            RemoteUtil.response(response, data, 1, "返回成功");
        } catch (Exception e) {
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    public void getDirectSupplyListByName(HttpServletRequest request, HttpServletResponse response) {
        try {
            String area = request.getParameter("area");
            String areaName = request.getParameter("areaName");
            if (StringUtils.isEmpty(area) || StringUtils.isEmpty(areaName)) {
                RemoteUtil.response(response, null, -2, "操作失败");
                return;
            }

            List<ThDirectSupply> data = directSupplyManager.getDirectSupplyListByName(area,
                    areaName);

            RemoteUtil.response(response, data, 1, "返回成功");
        } catch (Exception e) {
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    /**
     * 更新开通小区详情信息
     *
     * @param request
     * @param response
     */
    public void updateDirectSupply(HttpServletRequest request, HttpServletResponse response) {
        try {
            ThDirectSupply directSupply = (ThDirectSupply) RemoteUtil.request(request,
                    new ThDirectSupply());

            if (directSupply == null) {
                RemoteUtil.response(response, null, -2, "操作失败");
                return;
            }

            //【1】更新前先检索记录是否存在
            ThDirectSupply preDirectSupply = directSupplyManager.getDirectSupplyById(directSupply
                    .getId() + "");

            if (preDirectSupply == null) {
                RemoteUtil.response(response, null, -2, "操作失败");
                return;
            }

            //【2】更新记录
            directSupply.setMemo(preDirectSupply.getMemo());
            directSupply.setGmtCreate(preDirectSupply.getGmtCreate());
            directSupply.setGmtModified(new Date());
            boolean flag = directSupplyManager.updateDirectSupply(directSupply);

            if (flag) {
                RemoteUtil.response(response, null, 1, "返回成功");
            } else {
                RemoteUtil.response(response, null, -2, "操作失败");
            }

        } catch (Exception e) {
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    /**
     * 获取当前小区下的售卖商品列表
     *
     * @param request
     * @param response
     */
    public void getGoodsByDirectSupply(HttpServletRequest request, HttpServletResponse response) {

        try {
            //【1】查询该小区下所有的商品信息
            String directSupplyId = request.getParameter("directSupplyId");
            String cateId = request.getParameter("cateId");
            List<Goods> goods = directSupplyGoodsManager.getGoodsByDirectSupply(new Integer(
                    directSupplyId), "");

            //【2】懂事价格
            for (Goods good : goods) {
                int temp = Integer.MAX_VALUE;
                for (ThSku sku : good.getThSkus()) {
                    if (sku.getHidden() == 0 && sku.getID() < temp) {
                        temp = sku.getID();
                        good.setFakeSellOut(sku.getFakeSellout());
                        good.setSellOut(sku.getSellout());
                        good.setGoodsNumber(sku.getStock());
                    }
                    //董事特权只能享受分润总金额的90%
                    if (sku.getProfitShare() >= 0) {
                        int profitShare = (int) ((sku.getProfitShare()) * 0.9);
                        sku.setProfitShare(profitShare);
                    }
                }
            }

            //【2】是否进行分类
            List<Goods> goodList = new ArrayList<Goods>();
            if (!StringUtils.isEmpty(cateId)) {
                for (Goods good : goods) {
                    if (good.getGoodsType() == new Integer(cateId)) {
                        goodList.add(good);
                    }
                }
                goods = goodList;
            }

            //返回结果
            RemoteUtil.response(response, goods, 1, "返回成功");
        } catch (Exception e) {
            logger.error("获取当前小区下的售卖商品列表时发货时发生异常，异常信息：" + e);
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    /**
     * 获取附近小区信息
     *
     * @param request
     * @param response
     */
    public void getNearbyBlock(HttpServletRequest request, HttpServletResponse response) {

        try {
            //【1】3公里内经纬度范围
            double latitude = Double.parseDouble(request.getParameter("latitude"));//纬度
            double longitude = Double.parseDouble(request.getParameter("longitude"));//经度

            double range = 180 / Math.PI * 3 / 6372.797;// 3公里内经纬度差值转换，PI后面的值为公里数
            double lngR = range / Math.cos(latitude * Math.PI / 180);
            double maxLat = latitude + range;// 最大纬度
            double minLat = latitude - range;// 最小纬度
            double maxLng = longitude + lngR;// 最大经度
            double minLng = longitude - lngR;// 最小经度

            //【2】查询附近小区
            List<ThDirectSupply> directSupplys = directSupplyManager.getNearbyBlock(maxLat, minLat,
                    maxLng, minLng);

            if (directSupplys != null) {
                //【3】计算小区距离
                for (ThDirectSupply directSupply : directSupplys) {
                    double distance = LocationUtils.getDistance(latitude, longitude,
                            directSupply.getLatitude(), directSupply.getLongitude());
                    directSupply.setDistance((double) Math.round(distance * 10) / 10);
                    directSupply.setBlockPhoto(FrontConstants.GROUP_DIRECT_SUPPLY_PATH
                            + directSupply.getBlockPhoto());
                    directSupply.setLinkmanPhoto(FrontConstants.GROUP_DIRECT_SUPPLY_PATH
                            + directSupply.getLinkmanPhoto());
                }

                //【4】由远及近排序
                Collections.sort(directSupplys, new Comparator<ThDirectSupply>() {
                    public int compare(ThDirectSupply o1, ThDirectSupply o2) {
                        if (o1.getDistance() > o2.getDistance()) {
                            return 1;
                        }
                        if (o1.getDistance() == o2.getDistance()) {
                            return 0;
                        }
                        return -1;
                    }
                });
            }

            //【5】返回结果
            RemoteUtil.response(response, directSupplys, 1, "返回成功");
        } catch (Exception e) {
            logger.error("获取附近小区信息发生异常，异常信息：" + e);
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    /**
     * 关键字搜索小区
     *
     * @param request
     * @param response
     */
    public void searchBlock(HttpServletRequest request, HttpServletResponse response) {

        List<ThDirectSupply> directList = new ArrayList<ThDirectSupply>();
        String searchName = request.getParameter("searchName");

        try {
            //【1】查询所有的小区信息
            List<ThDirectSupply> directSupplys = directSupplyManager.getDirectSupplyList();

            //【2】根据关键字进行匹配
            for (ThDirectSupply directSupply : directSupplys) {
                String blockFullName = directSupply.getProvince() + directSupply.getCity()
                        + directSupply.getCounty() + directSupply.getTown()
                        + directSupply.getBlockName()
                        + directSupply.getBlockAddress();
                if (blockFullName.contains(searchName)) {
                    directSupply.setBlockPhoto(FrontConstants.GROUP_DIRECT_SUPPLY_PATH
                            + directSupply.getBlockPhoto());
                    directSupply.setLinkmanPhoto(FrontConstants.GROUP_DIRECT_SUPPLY_PATH
                            + directSupply.getLinkmanPhoto());
                    directList.add(directSupply);
                }
            }

            //【3】返回结果
            RemoteUtil.response(response, directList, 1, "返回成功");
        } catch (Exception e) {
            logger.error("关键字搜索小区发生异常，异常信息：" + e);
            RemoteUtil.response(response, null, -2, "操作失败");
        }
    }

    /**
     * 获取小区详情
     *
     * @param request
     * @param response
     */
    public void getBlockInfo(HttpServletRequest request, HttpServletResponse response) {

        String directId = request.getParameter("directId");
        JsonGroupDetail detail = new JsonGroupDetail();
        try {
            //【1】查询小区信息
            ThDirectSupply data = directSupplyManager.getDirectSupplyById(directId);
            data.setBlockPhoto(FrontConstants.GROUP_DIRECT_SUPPLY_PATH + data.getBlockPhoto());
            data.setLinkmanPhoto(FrontConstants.GROUP_DIRECT_SUPPLY_PATH + data.getLinkmanPhoto());
            detail.setBaseInfo(data);

            //【2】小区banner信息
            List<ThGroupBanners> banners = directSupplyManager.getGroupBannersList(new Integer(
                    directId), 1);
            if (!CollectionUtils.isEmpty(banners)) {
                for (ThGroupBanners banner : banners) {
                    banner.setImage(FrontConstants.GROUP_BANNER_PATH + banner.getImage());
                }
            }

            detail.setBannersList(banners);

            //【3】小区公告信息
            List<ThGroupBroadcast> broadcast = directSupplyManager.getGroupBroadcastList(
                    new Integer(directId), 1);
            detail.setBroadcastList(broadcast);

            //【4】小区个性化设置
            ThGroupPersonalSetting personalSetting = directSupplyManager
                    .getGroupPersonalSettingByState(new Integer(directId), 1);
            if (personalSetting != null) {
                personalSetting.setAdImg(FrontConstants.GROUP_PERSONAL_SETTING_PATH
                        + personalSetting.getAdImg());
                personalSetting.setLogo(FrontConstants.GROUP_PERSONAL_SETTING_PATH
                        + personalSetting.getLogo());
                personalSetting.setQrCode(FrontConstants.GROUP_PERSONAL_SETTING_PATH
                        + personalSetting.getQrCode());
            }
            detail.setSetting(personalSetting);

            //【5】人气+1
            ThDirectSupply data1 = directSupplyManager.getDirectSupplyById(directId);
            data1.setHeatPoint(data1.getHeatPoint() + 1);
            directSupplyManager.updateDirectSupply(data1);

            RemoteUtil.response(response, detail, 1, "返回成功");
        } catch (Exception e) {
            logger.error("获取小区详情发生异常，异常信息：" + e);
            RemoteUtil.response(response, null, -2, "操作失败");
        }
    }

    public void saveGroupDeliveryInfo(HttpServletRequest request, HttpServletResponse response) {

        String directSupplyId = request.getParameter("directSupplyId");
        String userId = request.getParameter("userId");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        try {
            ThGroupDeliveryAddr deliveryAddr = new ThGroupDeliveryAddr();
            deliveryAddr.setUserId(new Integer(userId));
            deliveryAddr.setDirectSupplyId(new Integer(directSupplyId));
            deliveryAddr.setName(name);
            deliveryAddr.setPhone(phone);
            deliveryAddr.setAddress(address);
            deliveryAddr.setOptime(System.currentTimeMillis());

            boolean flag = directSupplyManager.saveGroupDeliveryInfo(deliveryAddr);

            if (!flag) {
                RemoteUtil.response(response, null, -2, "操作失败");
            } else {
                RemoteUtil.response(response, null, 1, "返回成功");
            }

        } catch (Exception e) {
            logger.error("");
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    public void getGroupDeliveryInfo(HttpServletRequest request, HttpServletResponse response) {

        String directId = request.getParameter("directSupplyId");
        String userId = request.getParameter("userId");
        try {
            //【1】查询小区信息
            ThGroupDeliveryAddr data = directSupplyManager.getGroupDeliveryInfo(userId, directId);

            RemoteUtil.response(response, data, 1, "返回成功");
        } catch (Exception e) {
            logger.error("获取小区详情发生异常，异常信息：" + e);
            RemoteUtil.response(response, null, -2, "操作失败");
        }
    }

    public void getGroupBroadcast(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        ThGroupBroadcast broadcast = directSupplyManager.getGroupBroadcast(new Integer(id));
        RemoteUtil.response(response, broadcast, 1, "返回成功");
    }

    public void updateGroupDeliveryInfo(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        try {

            boolean flag = directSupplyManager.updateGroupDeliveryInfo(new Integer(id), name,
                    phone, address);

            if (!flag) {
                RemoteUtil.response(response, null, -2, "操作失败");
            } else {
                RemoteUtil.response(response, null, 1, "返回成功");
            }

        } catch (Exception e) {
            logger.error("");
            RemoteUtil.response(response, null, -2, "操作失败");
        }

    }

    /**
     * @param directSupplyGoodsManager the directSupplyGoodsManager to set
     */
    public void setDirectSupplyGoodsManager(DirectSupplyGoodsManager directSupplyGoodsManager) {
        this.directSupplyGoodsManager = directSupplyGoodsManager;
    }

    public void setDirectSupplyManager(DirectSupplyManager directSupplyManager) {
        this.directSupplyManager = directSupplyManager;
    }

    public static void main(String[] args) {
        double d = 114.145;
        d = (double) Math.round(d * 10) / 10;
        System.out.println(d);
    }

}
